/*
	The MIT License

	Copyright (c) 2008 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/
// win_inputsys.cpp - mouse and keyboard stuff


#include "..\global.h"
#include "win_inputsys.h"
#include "win_key_list.h"


/*-----------------------------------------------------------------------------
	EXPORT Stuff
-----------------------------------------------------------------------------*/
DLL_EXPORT IInputSystem *CreateInputSystem(const ap_t &ap)
{
	return new EWinInputSystem(ap);
}

DLL_EXPORT void DestroyInputSystem(IInputSystem *is)
{
	delete is;
}


/*-----------------------------------------------------------------------------
	Input stuff
-----------------------------------------------------------------------------*/
static IConsole		*con;
static IFileSystem	*fs;
static IShell		*shell;



EWinInputSystem::EWinInputSystem(const ap_t& ap)
{
	con		=	ap.con;
	shell	=	ap.shell;
	fs		=	ap.fs;

	LOGF("INIT : Input system\r\n");
	
	for (int i=0; i<256; i++)
	{
		bindlist[i].name		=	OS_KEY_LIST[i];
		bindlist[i].is_pressed	=	false;
		bindlist[i].bind_cmd	=	"";
	}
	
	in_show_cursor	=	shell->RegisterVar("in_show_cursor", "0", 0);
	
	shell->AddCommand("bind",		(EShellCmd_f)Bind_f,			this);
	shell->AddCommand("UnbindAll",	(EShellCmd_f)UnbindAll_f,	this);
	shell->AddCommand("listBinds",	(EShellCmd_f)ListBinds_f,	this);
	shell->AddCommand("listKeys",	(EShellCmd_f)ListKeys_f,	this);
}


EWinInputSystem::~EWinInputSystem(void)
{
	ClipCursor(NULL);
	while(ShowCursor(TRUE)<0) ;
	LOGF("SHUTDOWN : Input system\r\n");
}


//
//	EWinInputSystem::ProcessInput
//
void EWinInputSystem::ProcessInput(void *wnd, bool enable_scan, bool relative_mmove, 
							bool clip_cursor, bool show_cursor, mouseInput_s &mouse)
{
	HWND	hWnd	=	(HWND)wnd;
	
	if (GetActiveWindow()!=hWnd) {
		enable_scan = false;
		clip_cursor	= false;
	}
	
	//
	//	KEYBOARD :
	//
	unsigned char keys[256];
	char	cmd[1024];
	GetKeyboardState(keys);
	
	for (int i=0; i<256; i++)
	{
		if (!bindlist[i].name) continue;
		if (bindlist[i].bind_cmd.length()==0) continue;
		
		strcpy(cmd, bindlist[i].bind_cmd.c_str());
		
		if ((keys[i] & 0x80) && !bindlist[i].is_pressed && enable_scan)
		{
			shell->ExecuteString(va("%s;", cmd));
			bindlist[i].is_pressed = true;
		}
		
		if (  ((!(keys[i] & 0x80)) || !enable_scan) && bindlist[i].is_pressed)
		{
			bindlist[i].is_pressed = false;
			if (cmd[0]=='+') 
			{
				cmd[0]='-';
				shell->ExecuteString(va("%s;", cmd));
			}
		}
	}

	//
	//	MOUSE :
	//
	if (true)
	{
		if (!show_cursor) {
			while(ShowCursor(FALSE)>=0) ;
		}
	
		RECT	rect;
		WINDOWINFO	info;
		GetWindowRect(hWnd, &rect);
		GetWindowInfo(hWnd, &info);

		//	FIXME : bad practice, we dont know anything about this window... 
		if (info.dwStyle & WS_POPUP) {
		} else {
			rect.left	+= ( GetSystemMetrics(SM_CXFIXEDFRAME) );
			rect.right	-= ( GetSystemMetrics(SM_CXFIXEDFRAME) );
			rect.top	+= ( GetSystemMetrics(SM_CYFIXEDFRAME)+GetSystemMetrics(SM_CYCAPTION) );
			rect.bottom -= ( GetSystemMetrics(SM_CYFIXEDFRAME) );
		}
		int x = rect.left;
		int y = rect.top;

		POINT	pnt;
		GetCursorPos(&pnt);
		int cx	= (rect.left + rect.right - x)/2;
		int cy	= (rect.top  + rect.bottom - y)/2;

		mouse.x	 = pnt.x - x;
		mouse.y	 = pnt.y - y;
		mouse.dx = cx - mouse.x;
		mouse.dy = cy - mouse.y;
		mouse.left		=	(0 != (GetKeyState(VK_LBUTTON) & 0x80));
		mouse.middle	=	(0 != (GetKeyState(VK_MBUTTON) & 0x80));
		mouse.right		=	(0 != (GetKeyState(VK_RBUTTON) & 0x80));

		if (relative_mmove) {
			SetCursorPos(cx, cy);
		}
		if (clip_cursor) {
			ClipCursor(&rect);
		}
	}
	else
	{
		while(ShowCursor(TRUE)<0) ;
		ClipCursor(NULL);
		mouse.dx	= 0;
		mouse.dy	= 0;
		mouse.x		= 0;
		mouse.x		= 0;
		mouse.left	= false;
		mouse.middle= false;
		mouse.right	= false;
	}
}


//
//	EWinInputSystem::AppendKeyBindings
//
void EWinInputSystem::AppendKeyBindings(const char *filename)
{
	IFile	*f	=	fs->FileOpen(filename, FS_OPEN_APPEND);
	
	f->Printf("\r\n\r\n// key bindings :\r\n");
	//f->Printf("UnbindAll\r\n");
	
	for (int i=0; i<256; i++)
	{
		if (bindlist[i].name) { 
			if (bindlist[i].bind_cmd.length()==0) {
				continue;
			}
			
			f->Printf("bind %-12s \"%s\"\r\n", bindlist[i].name, bindlist[i].bind_cmd.c_str());
		}
	}
	
	fs->FileClose(f);
}


uint EWinInputSystem::GetKeyByCmd ( const char *cmd )
{	
	for(int i = 0; i < 256; i++)
	{		
		if ( strcmpi(bindlist[i].bind_cmd.c_str(), cmd) ==0 ) return i;
		
	}
	return 0;
}
/*-----------------------------------------------------------------------------
	Stuff...
-----------------------------------------------------------------------------*/

//
//	EWinInputSystem::ListBinds_f
//
void EWinInputSystem::ListBinds_f(EWinInputSystem *self, int argc, const char **argv)
{
	uint num = 0;

	for (int i=0; i<256; i++)
	{
		if (self->bindlist[i].name) {
			if (self->bindlist[i].bind_cmd.length()==0) continue;
			
			LOGF("  %-12s = %s\r\n", self->bindlist[i].name, self->bindlist[i].bind_cmd.c_str());
			num++;
		}
	}
	LOGF("%d keys are bounded\r\n", num);
}


//
//	EWinInputSystem::ListKeys_f
//
void EWinInputSystem::ListKeys_f(EWinInputSystem *self, int argc, const char **argv)
{
	uint num = 0;
	
	LOGF("\r\n");
	for (int i=0; i<256; i++)
	{
		if (self->bindlist[i].name) {
			LOGF("  0x%02X : %s\r\n", i, self->bindlist[i].name);
		}
	}

	//for (int i=0; i<256; i++)
	//{
	//	if (self->bindlist[i].name) {
	//		LOGF("#define KEY_%-20s 0x%X\r\n", self->bindlist[i].name, i);
	//	}
	//}

	//LOGF("const char *KEY_LIST[256] = {\r\n");
	//for (int i=0; i<256; i++)
	//{
	//	if (i && i%16==0) LOGF("\r\n", i);

	//	LOGF("  /* 0x%02X */  ", i);
	//	
	//	if (self->bindlist[i].name) {
	//		LOGF("\"%s\"", self->bindlist[i].name);
	//	} else {
	//		LOGF("NULL", self->bindlist[i].name);
	//	}

	//	LOGF(",\r\n");
	//}
	//LOGF("};\r\n");
}


//
//	EWinInputSystem::Bind_f
//
void EWinInputSystem::Bind_f(EWinInputSystem *self, int argc, const char **argv)
{
	if (argc!=3)
	{
		LOGF("usage : bind <keyname> <cmd> - bind\r\n");
		LOGF("        bind <keyname> \"'\"   - unbind\r\n");
		return;
	}
	
	uint key	=	self->GetKeyCode(argv[1]);
	if (key==0) RAISE_EXCEPTION(va("unknown key \"%s\"", argv[1]));
	
	self->bindlist[key].bind_cmd	=	argv[2];
}


//
//	EWinInputSystem::UnbindAll_f
//
void EWinInputSystem::UnbindAll_f(EWinInputSystem *self, int argc, const char **argv)
{
	for (uint i=0; i<256; i++) self->bindlist[i].bind_cmd = "";
}


//
//	EWinInputSystem::GetKeyCode
//
uint EWinInputSystem::GetKeyCode(const char *name)
{
	for (uint i=0; i<256; i++)
	{
		if ( bindlist[i].name ) {
			if ( strcmpi(bindlist[i].name, name)==0) return i;
		}
	}
	
	return 0;
}













